package com.cloudshadow.platform.server.common.base.aspect;

import com.cloudshadow.platform.infrastrcture.context.ClientDataContext;
import com.cloudshadow.platform.infrastructure.exception.ErrInfoException;
import com.cloudshadow.platform.infrastructure.exception.ErrorInfos;
import com.cloudshadow.platform.server.common.base.annotation.NoLogin;
import com.cloudshadow.platform.server.common.base.req.BaseReq;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.lang.reflect.Method;

@Aspect
@Configuration
@Order(AspectOrders.AUTHCHECK_ORDER)
public class AuthCheckAspect extends ControllerAspect {
    

    @Override
    @Around(value = "pointCut()")
    protected Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        // 先清空下线程
        clearBinding();
        // 在Spring的环境里，signature就是MethodSignature
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        // 获取Method
        Method method = methodSignature.getMethod();
        // 方法上没有申明@NoLogin且类上也没有申明@NoLogin，则检查登录状况
        if (method.isAnnotationPresent(NoLogin.class)
                || method.getDeclaringClass().isAnnotationPresent(NoLogin.class)) {
            return pjp.proceed();
        }
        Object form = pjp.getArgs()[0];
        if (form == null || !(form instanceof BaseReq)) {
            throw new ErrInfoException(ErrorInfos.ClientErr.NO_LOGIN);
        }



        // 执行业务
        return pjp.proceed();
    }
    
//    private void checkAndBindLoginInfo(BaseReq form) {
//        // 获取携带的access_token
//        String access_token = form.getAccess_token();
//        // 获取会话身份对象
//        ClientSession identity = sessionService.fetchClientCacheByUserToken(access_token);
//        if (null == identity) {
//            // 如果会话身份对象不存在则表示未登录或已超时
//            throw new ErrInfoException(ErrorInfos.ClientErr.NO_LOGIN);
//        }
//        sessionService.refreshToken(identity);
//        contextService.setClientSession(identity);
//    }
//
    private void clearBinding() {
        ClientDataContext.clear();
    }
}
